//
//  YJSQLiteManager.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/24.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit
import FMDB

/*
 数据库操作:
 1.打开数据库
 2.创建表
 3.操作数据
 */
class YJSQLiteManager: NSObject {
    static let shared = YJSQLiteManager()
    
    var dbQueue: FMDatabaseQueue
    
    fileprivate override init() {
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/status.db"
        JPrint("dbPath: \(path)")
        // 如果数据不存在会创建,并打开
        dbQueue = FMDatabaseQueue(path: path)
        
        super.init()
        
        createTable()
    }
    
    fileprivate func createTable() {
        let tablesPath = Bundle.main.path(forResource: "tables.sql", ofType: nil)!
        let sqls = try! String(contentsOfFile: tablesPath)
        
        // 执行sql
        dbQueue.inTransaction { (db, rollback) in
            if(db?.executeStatements(sqls))! {
                JPrint("创建表成功")
            } else {
                JPrint("创建表失败")
            }
        }
    }
}
